package com.javabasic.basic_learning;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mir.xiong
 * @version 1.0
 * @description Java引用传递
 * @see
 * - [Java 到底是值传递还是引用传递？](https://www.zhihu.com/question/31203609/answer/50992895)
 * - [以Integer类型传参值不变来理解Java值传参](https://blog.csdn.net/weixin_30275415/article/details/102450685)
 * @since Created by work on 2021/12/24 12:03 上午
 */
public class ReferenceTransmission {

    class Entity {
        int x;
    }

    public void inc(int x) {
        x++;
    }

    public void inc(Entity entity) {
        inc(entity.x);
    }

    @Test
    public void test1() {
        int x = 0;
        inc(x);
        System.out.println(x);

        Entity entity = new Entity();
        inc(entity);
        System.out.println(entity.x);
    }


    class Entity2 {
        Integer x = 0;
    }

    public void inc2(Integer x) {
        x++;
    }

    public void inc2(Entity2 entity2) {
        inc(entity2.x);
    }

    @Test
    public void test2() {
        Integer x = 0;
        inc2(x);
        System.out.println(x);

        Entity2 entity2 = new Entity2();
        inc2(entity2);
        System.out.println(entity2.x);
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        add(list);
        for (Integer j : list) {
            System.err.print(j+",");;
        }
        System.err.println("");
        System.err.println("*********************");
        String a="A";
        append(a);
        System.err.println(a);
        int num = 5;
        addNum(num);
        System.err.println(num);
    }

    static void add(List<Integer> list){
        list.add(100);
    }

    /**
     * String 是一个不变类
     * @param str
     */
    static void append(String str){
        str+="is a";
    }


    static void addNum(int a){
        a=a+10;
    }

    /**
     * 形参的引用变了，原来穿过的参数还是没变
     * @param a
     */
    static void addNum(Integer a){
        /**
         * 下面这个语句等价于：a = a + Integer.valueOf(10);
         * 就是改变了形参的引用
         */
        a=a+10;
    }
}
